import React, { useState, useRef, useEffect } from 'react'
import { LuckyWheel } from '@lucky-canvas/react';
import { Button, Toast, Space, Modal, Avatar } from "antd-mobile";
import callFeedback from "@/components/common/modalFeedback";
import requewt from "@/utils/requewt";
import { API } from "@/config/api";
import { isValidArr, navigateTo } from "@/utils";
import useRecord from "@/components/pages/stores/useRecord";
import { FeedbackComp } from "@/components/pages/wheel";
import { PrizeComp, RuleComp } from "@/components/common";
import Head from "next/head";
import { BASE_PATH } from "@/config";

const pageName = "wheel";
const klassName = pageName.replace(/\./g, '-');

function celebrate() {
  const box = document.getElementById(`box`);

  let count = 200;
  let defaults = {
    zIndex: 9999,
    origin: {
      x: 0.5,
      // since they fall down, start a bit higher than random
      y: .5 || 0
    }
  };

  function fire(particleRatio, opts) {
    confetti(
      Object.assign({}, defaults, opts, {
        particleCount: Math.floor(count * particleRatio)
      })
    );
  }

  fire(0.25, {
    spread: 26,
    startVelocity: 55
  });
  fire(0.2, {
    spread: 60
  });
  fire(0.35, {
    spread: 100,
    decay: 0.91,
    scalar: 0.8
  });
  fire(0.1, {
    spread: 120,
    startVelocity: 25,
    decay: 0.92,
    scalar: 1.2
  });
  fire(0.1, {
    spread: 120,
    startVelocity: 45
  });
}

export default function Wheel(props) {
  const {user} = props;

  const {avatar, nickname} = user?.extra || {};

  const lotterys = useRecord(state => state.lotterys);
  const games = useRecord(state => state.games);
  const update = useRecord(state => state.update);


  const myLucky = useRef();
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [current, setCurrent] = useState(undefined);

  const [blocks] = useState([
    {
      padding: '32px',
      imgs: [{
        src: `${BASE_PATH}/img/wheel/wheel-bg.png`,
        width: '100%',
        height: '100%',
      }]
    }

  ])
  const [prizes, setPrizes] = useState([])
  const [buttons] = useState([
    {
      radius: '75px',
      imgs: [
        {
          src: `${BASE_PATH}/img/wheel/wheel-btn.png`,
          width: '100px',
          height: '100px',
          top: `-50px`
        }
      ],
    }
  ])

  useEffect(() => {
    (async () => {
      await Promise.all([
        await compHandler.fetch(),
        await compHandler.check()
      ])
    })()

    return () => {
      Modal?.clear();
      Toast.clear();
    }
  }, [])

  useEffect(() => {
    if (!isValidArr(prizes)) return
    setTimeout(() => {
      myLucky?.current?.init()
    }, 100)
  }, [prizes])

  const compHandler = {
    // 检测抽奖次数
    check: async () => {
      const resp = await requewt(API.lottery.remain);
      if (resp?.error_code !== 0 || resp?.msg !== `ok`) {
        return
      }
      update(`lotterys`, resp.data);
    },
    // 点击按钮开始抽奖
    gamble: async () => {

      if (lotterys <= 0) {
        FeedbackComp({
          item: {
            icon: `https://yinli-qixi-run.varwey.com/2023/3w-ktv-battle-230612/img/price/item-4.png`,
            category: 99,
          }
        })
        return
      }

      if (loading) return
      Toast.show({content: `请求中`, icon: `loading`})
      setLoading(true);
      const options = {method: `POST`}
      const resp = await requewt(API.lottery.draw, options);
      console.log(`gamble.resp`, resp);
      setTimeout(() => {
        setLoading(false)
        Toast.clear();
      }, 300);

      if (resp?.[`error_code`] !== 0 || resp?.[`msg`] !== `ok`) {
        // 特殊的展示方式
        if (resp[`error_code`] === 1001) {
          FeedbackComp({
            item: {
              icon: `https://yinli-qixi-run.varwey.com/2023/3w-ktv-battle-230612/img/price/item-4.png`,
              category: 99,
            }
          })
        } else {
          callFeedback({
            title: <div dangerouslySetInnerHTML={{__html: resp?.msg || `失败!`}}>
            </div>
          })
        }

        return
      }
      const gift = resp.data;
      const index = data.findIndex(e => e.name === gift.name);
      // console.log(resp.data)
      // console.log(gift, index)
      if (index < 0) return Toast.show({content: `失败！`})

      setCurrent(resp.data);
      myLucky.current?.play();
      setTimeout(() => {
        myLucky.current?.stop(index)
      }, 1000)
    },
    // 展示中奖结果
    percent: (item) => {
      update(`lotterys`, item.today_remain_draw_num);
      FeedbackComp({item, handler: compHandler})
    },
    // 获取奖品
    fetch: async () => {
      Toast.show({content: `奖品加载中`, icon: `loading`})
      setLoading(true);
      const resp = await requewt(API.prize.entire);
      setTimeout(() => {
        setLoading(false);
        Toast.clear();
      }, 800);
      if (resp?.[`error_code`] !== 0 || resp?.[`msg`] !== `ok`) {
        return
      }
      compHandler._filterPrize(resp.data)
      setData(resp.data)
    },
    _filterPrize: prs => {
      if (!isValidArr(prs)) return [];
      let _prizes = [];
      prs.forEach((item, i) => {
        let tmp = {
          _id: item.id,
          background: i === 0 ? `#ffe9e8` : i % 2 === 0 ? `#bed3ee` : `#fff`,
          fonts: [
            {
              top: '15%',
              text: item.name,
              fontStyle: "Changan Uni",
              fontSize: `18px`,
              lengthLimit: `65%`,
              wordWrap: false,
              fontColor: `#3a86e4`
            }
          ],
          imgs: [
            {
              src: item.icon ? item.icon : ``,
              width: '25%',
              top: '70%'
            }
          ]
        }
        _prizes.push(tmp);
      })
      setPrizes(_prizes)
    },
    // 我的奖品
    prize: async () => {
      const m = callFeedback({
        bodyClassName: `act-feedback-modal close-at-center-bottom`,
        content: <div className="inner"><PrizeComp /></div>,
        actions: <>
          <Button shape={`rounded`}
                  loading={loading}
                  className="act-btn act-btn-bevel"
                  onClick={e => navigateTo(`/landing`)}
          >
            返回首页
          </Button>
          <Button shape={`rounded`}
                  loading={loading}
                  className="act-btn act-btn-bevel"
                  onClick={async e => m.close()}
          >
            去抽奖
          </Button>
        </>,
        closeOnAction: true,
        closeOnMaskClick: true,
      })
    },
    rule: async () => {
      const m = callFeedback({
        bodyClassName: `rule-modal`,
        title: <>星动战队大作战</>,
        content: <div className="inner"><RuleComp /></div>,
        actions: [],
        closeOnAction: true,
        closeOnMaskClick: false,
      })
    }
  }

  return (
    <>
      <Head>
        <title>转盘抽奖</title>
      </Head>
      <div className={`p-${klassName} page page-thd`}>
        <div className="inner">
          <div className="position-center">
            <div className="award-pool">

              <div className="award-header">
                <div className="title">
                  幸运大转盘
                </div>
              </div>

              <div className="award-wheel">
                {
                  isValidArr(prizes) &&
                  <LuckyWheel ref={myLucky}
                              id={`test`}
                              width="88vw"
                              height="88vw"
                              blocks={blocks}
                              prizes={prizes}
                              buttons={buttons}
                              onStart={() => compHandler.gamble()}
                              onEnd={prize => { // 抽奖结束会触发end回调
                                compHandler.percent(current)
                                // callFeedback({title: `恭喜你抽到 ${prize.fonts[0].text} 号奖品`})
                              }}
                  />
                }

              </div>

              <div className="award-footer">
                <div className="remain">您还有 <big>{lotterys}</big> 次抽奖机会</div>
              </div>


              <div className="award-ope">
                <Button shape={`rounded`} className="act-btn act-btn-bevel"
                        onClick={e=>navigateTo(`/landing`)}
                >
                  返回首页
                </Button>
                <Space className="btn-group mt-3">
                  <Button shape={`rounded`} className="act-btn act-btn-bevel"
                          onClick={compHandler.prize}
                  >
                    我的奖品
                  </Button>

                  <Button shape={`rounded`} className="act-btn act-btn-bevel"
                          onClick={e => navigateTo(`/rank/current`)}
                  >
                    游戏排行榜
                  </Button>
                </Space>

              </div>
            </div>

          </div>
        </div>

      </div>
    </>
  )
}

Wheel.need2auth = true;
Wheel.pageName = pageName;